import React, { useRef, useState, useEffect } from "react";
import '@chatui/core/es/styles/index.less';
import Chat, { Bubble, useMessages } from '@chatui/core';
import '@chatui/core/dist/index.css';




export default function ChatBox(props) {
    const { messages, appendMsg, setTyping, resetList } = useMessages([]);
    const { chatId, msgList, reply } = props
    useEffect(() => {
        console.log('resetList', msgList, chatId)
        resetList(msgList)
    }, [chatId])

    useEffect(() => {
        props.onMessagesChange(messages)
    }, [messages])

    useEffect(() => {
        if (!reply) return;
        appendMsg({
            type: 'text',
            content: { text: reply },
        });
    }, [reply])

    function handleSend(type, val) {
        if (type === 'text' && val.trim()) {
            appendMsg({
                type: 'text',
                content: { text: val },
                position: 'right',
            });
            props.onSendMessage(val)
            setTyping(true);
        }
    }

    function renderMessageContent(msg) {
        const { content } = msg;
        return <Bubble content={content.text} />;
    }

    return (
        <Chat
            navbar={{ title: chatId }}
            messages={messages}
            renderMessageContent={renderMessageContent}
            onSend={handleSend}
        />
    );
}